import json,time
import requests
import urllib.request
from django.shortcuts import render
from bs4 import BeautifulSoup
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import  HttpResponse
from django.template.loader import  get_template

import re
from kalf.models import Product
from django.contrib.auth.hashers import make_password,check_password


# URL = "http://www.kuborui.net/materiel/materiel?page=2&materiel_name=&materiel_type_id=2&materiel_use=&warehouse_id="
URL = "http://www.bjkalf.com/WeiXin/Order.aspx"
# URL = "http://www.bjkalf.com/WeiXin/Index2.aspx"

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    "Cookie": "td_cookie=18446744070206583801; ASP.NET_SessionId=zy2mvlex3kavsvtpy1jihenm;td_cookie=18446744070206192288",
    "Host": "www.bjkalf.com",
    # 'Referer':'http://www.bjkalf.com/WeiXin/Index2.aspx',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
}

def get_html():
    html =""
    response = requests.get(URL, headers=headers)  # 发送网络请求，获取服务器响应
    time.sleep(10)
    if response.status_code == 200:
        html = BeautifulSoup(response.text, "html.parser")
    return html

#获取订单信息；
def getOrder(request):
    #response = requests.get(URL,headers=headers)  # 发送网络请求，获取服务器响应
    #time.sleep(15)
    html = get_html()
    if len(html) !=0:
        #html = BeautifulSoup(response.text, "html.parser")
        #tables = html.findAll('table')
        tables = html.find_all(class_="tb")
        v_cnt = len(tables)
        list = []
        print(v_cnt)
        if len(tables):
            tab = tables[0]
            i =0
            p_name = ""
            unit = ""
            ydsl = ""
            bhsl = ""
            dhsl = ""
            for tr in tab.find_all(class_="tbtbody"):
                i=i+1
                if i==1:
                    for td in tr.findAll('td'):
                        if len(td.getText().strip()) >0:
                            p_name = td.getText().strip()
                if i==2:
                    j =1
                    for td in tr.findAll('td'):
                        if j==1:
                            ydsl = td.getText().strip()
                            ydsl =re.sub("\D","",ydsl)
                        if j==2:
                            bhsl = td.getText().strip()
                            bhsl = re.sub("\D","",bhsl)
                        if j==3:
                            dhsl = td.getText().strip()
                            dhsl =re.sub("\D","",dhsl)
                        j=j+1
                if i==3:
                    for td in tr.findAll('td'):
                        if len(td.getText())>0:
                            vars = td.getText().split('：')
                            unit = vars[1]
                            str_var =[]
                            str_var.append(p_name)
                            str_var.append(ydsl)
                            str_var.append(bhsl)
                            str_var.append(dhsl)
                            str_var.append(unit)
                            list.append(str_var)
                            p_name = ""
                            unit = ""
                            ydsl = ""
                            bhsl = ""
                            dhsl = ""
                            i=0
        #print(str(i))
        return list


#抓取订货日期、发货日期、订单号
def getOrderInfo(request):
    #response = requests.get(URL, headers=headers)  # 发送网络请求，获取服务器响应
    #time.sleep(15)
    html = get_html()
    data = {
        'code': '0',
        'order_date': "",
        'doco': "",
        'ship_date': ""
    }
    if len(html) !=0:
        #html = BeautifulSoup(response.text, "html.parser")
        tables = html.find_all(class_="tb")
        v_cnt = len(tables)
        print(v_cnt)
        order_date =""
        doco =""
        ship_date =""
        if len(tables):
            tab = tables[0]
            for tr in tab.find_all(class_="tbth"):
                for td in tr.find_all(class_="tbtdleft"):
                    order_date = td.getText().strip()

            for tr in tab.find_all(class_="tbtfoot1"):
                for td in tr.find_all(class_="tbtdleft"):
                    str_vars = td.getText().split('：')
                    doco = str_vars[1]

            for tr in tab.find_all(class_="tbtfoot2"):
                i =0
                for td in tr.findAll('td'):
                    i=i+1
                    if i==1:
                        str_varss = td.getText().strip().split('：')
                        ship_date = str_varss[1]
            data ={
                'code':'1',
                'order_date':order_date,
                'doco':doco,
                'ship_date':ship_date
            }
    return data


# WXProductHandler.ashx
# ProductList.aspx
def getProduct(request):
    text = ''
    str = ''
    # URL = "http://www.kuborui.net/materiel/materiel?page=2&materiel_name=&materiel_type_id=2&materiel_use=&warehouse_id="
    URL2 = "http://www.bjkalf.com/WeiXin/WXProductHandler.ashx"

    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Cookie': 'td_cookie=18446744069528482825; ASP.NET_SessionId=2pls1gg52b3dwasausxrz4m3; uname=WU0039; pwd=9514753',
        'Host': 'www.bjkalf.com',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
    }

    response = requests.get(URL2, headers=headers)  # 发送网络请求，获取服务器响应
    time.sleep(10)
    if response.status_code == 200:
        html = BeautifulSoup(response.text, "html.parser")
        forms = html.findAll('form')
        tables = forms.findAll('form')
        v_cnt = len(tables)
        print(v_cnt)
        if len(tables):
            tab = tables[0]
            # v_cnt1 = len(tab.find_all(clas_="tbtbody"))
            # print(v_cnt1)
            i = 0
            list =[]
            for tr in tab.find_all(class_="tbtbody"):
                i = i + 1
                arrs = []
                for td in tr.findAll('td'):
                    txt = td.getText().strip()
                    if txt != '':
                        if i==1:
                            p_name = txt
                        if i==2:
                            arrs.append(txt)
                        if i==3:
                            unit=txt
                        print(txt)
                list.append(p_name)
                list.append(arrs)
                list.append(unit)
                print(list)
    return HttpResponse(json.dumps(list))

def get_local_product_back(request):

    URL2 = "http://127.0.0.1:8000/P/"

    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Host': '127.0.0.1:8000',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
    }

    response = requests.get(URL2, headers=headers)  # 发送网络请求，获取服务器响应
    time.sleep(5)
    v_cnt = 0
    if response.status_code == 200:
        html = BeautifulSoup(response.text, "html.parser")
        forms = html.findAll('form')
        product = Product()
        num = len(forms)
        for index in range(0,num):
            form = forms[index]
            vars = form.getText().split('\n')  #直接获取信息；
            if len(vars):
                p_name = vars[6]
                p_price = vars[11][1:]
                p_spec = vars[17]
                p_unit = p_spec[0:1]
            sub_strform = str(form)[0:30]      #需要转换为字符串，才能截取
            p_code = re.sub("\D","",sub_strform) #通过此方法获取原料编码
            #v_cnt += product.save_product_data(p_code,p_name,p_spec,p_unit,p_price,"10001")
    return HttpResponse(str(v_cnt))

def get_local_product(request):

    URL2 = "http://127.0.0.1:8000/P/"

    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'Host': '127.0.0.1:8000',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
    }

    response = requests.get(URL2, headers=headers)  # 发送网络请求，获取服务器响应
    time.sleep(5)
    v_cnt = 0
    if response.status_code == 200:
        html = BeautifulSoup(response.text, "html.parser")
        forms = html.findAll('form')
        num = len(forms)

        product = Product()
        for index in range(0, num):
            form = forms[index]
            #vars = form.getText().split('\n')  #直接获取信息；
            sub_strform = str(form)[0:30]      #需要转换为字符串，才能截取
            p_code = re.sub("\D","",sub_strform) #通过此方法获取原料编码
            tables =form.findAll('tbody')
            tab = tables[0]

            if len(tab):
                trs = tab.findAll('tr')
                tds = trs[0].findAll('td')
                p_name = tds[1].getText().strip()
                print(p_name)
                p_price =tds[2].getText().strip()[1:]
                print(p_price)
                tds2 = trs[1].findAll('td')
                p_spec = tds2[0].getText().strip()
                p_unit = p_spec[0:1]
                print(p_unit)
                v_cnt += product.save_product_data(p_code, p_name, p_spec, p_unit, p_price, "10001")
    return HttpResponse(str(v_cnt))
